import { Cell, Node, Edge } from '@antv/x6';
import ELNode from './node';
import {
  ConditionTypeEnum,
  LITEFLOW_EDGE,
  NODE_TYPE_END,
  NODE_TYPE_START,
} from '../constant';
import { ThenOperator } from './el';

/**
 * EL表达式的根节点——EL表达式的所有延伸内容，都是在根节点上开始的。
 * 例如一个串行编排(THEN)：
 * (1) EL表达式形式：THEN(a, b, c, d)
 * (2) JSON表示形式：
 * {
    type: ConditionTypeEnum.THEN,
    children: [
      { type: NodeTypeEnum.COMMON, id: 'a' },
      { type: NodeTypeEnum.COMMON, id: 'b' },
      { type: NodeTypeEnum.COMMON, id: 'c' },
      { type: NodeTypeEnum.COMMON, id: 'd' },
    ],
  }
 */
export default class Chain extends ELNode {
  constructor(children) {
    super();
    this.type = ConditionTypeEnum.CHAIN;
    this.children = children || [];
    this.startNode = null;
    this.endNode = null;
  }

  /**
   * 创建Chain实例
   */
  static create(children) {
    return new Chain(children);
  }

  /**
   * 转换为X6的图数据格式
   */
  toCells() {
    this.resetCells();
    const cells = this.cells;
    
    // 1. 首先：添加一个开始节点
    const start = Node.create({
      shape: NODE_TYPE_START,
      attrs: {
        label: { text: '开始' },
      },
    });
    start.setData(
      {
        model: this,
        toolbar: {
          prepend: false,
          append: true,
          delete: false,
          replace: false,
        },
      },
      { overwrite: true },
    );
    cells.push(start);
    this.startNode = start;

    // 2. 其次：解析已有的节点
    let last = start;
    this.children.forEach((x) => {
      x.toCells();
      cells.push(
        Edge.create({
          shape: LITEFLOW_EDGE,
          source: last.id,
          target: x.getStartNode().id,
        }),
      );
      last = x.getEndNode();
    });

    // 3. 最后：添加一个结束节点
    const end = Node.create({
      shape: NODE_TYPE_END,
      attrs: {
        label: { text: '结束' },
      },
    });
    end.setData(
      {
        model: this,
        toolbar: {
          prepend: true,
          append: false,
          delete: false,
          replace: false,
        },
      },
      { overwrite: true },
    );
    cells.push(end);
    this.endNode = end;

    // 4. 连接最后一个节点到结束节点
    if (last !== start) {
      cells.push(
        Edge.create({
          shape: LITEFLOW_EDGE,
          source: last.id,
          target: end.id,
        }),
      );
    }

    return cells;
  }

  /**
   * 转换为EL表达式
   */
  toEL(prefix = '') {
    if (this.children.length === 0) {
      return '';
    }
    return this.children[0].toEL(prefix);
  }

  /**
   * 数据属性转换为EL表达式
   */
  dataPropertyToEL(prefix = '') {
    const properties = this.getProperties();
    let el = '';

    if (properties.id) {
      el += `.id("${properties.id}")`;
    }

    if (properties.tag) {
      el += `.tag("${properties.tag}")`;
    }

    return el;
  }

  /**
   * 转换为JSON
   */
  toJSON() {
    const json = {
      type: this.type,
      collapsed: this.collapsed,
    };

    if (this.children && this.children.length > 0) {
      json.children = this.children.map(child => child.toJSON());
    }

    const properties = this.getProperties();
    if (properties && Object.keys(properties).length > 0) {
      json.properties = properties;
    }

    return json;
  }

  /**
   * 在后面添加新节点
   */
  append(newNode) {
    if (this.children.length === 0) {
      return this.appendChild(newNode);
    }
    return this.children[this.children.length - 1].append(newNode);
  }

  /**
   * 在后面添加子节点
   */
  appendChild(newNode, index) {
    newNode.parent = this;
    if (typeof index === 'number') {
      this.children.splice(index, 0, newNode);
    } else if (index) {
      const _index = this.children.indexOf(index);
      if (_index !== -1) {
        this.children.splice(_index + 1, 0, newNode);
      } else {
        this.children.push(newNode);
      }
    } else {
      this.children.push(newNode);
    }
    return true;
  }

  /**
   * 在前面添加新节点
   */
  prepend(newNode) {
    if (this.children.length === 0) {
      return this.prependChild(newNode);
    }
    return this.children[0].prepend(newNode);
  }

  /**
   * 在前面添加子节点
   */
  prependChild(newNode, index) {
    newNode.parent = this;
    if (typeof index === 'number') {
      this.children.splice(index, 0, newNode);
    } else if (index) {
      const _index = this.children.indexOf(index);
      if (_index !== -1) {
        this.children.splice(_index, 0, newNode);
      } else {
        this.children.unshift(newNode);
      }
    } else {
      this.children.unshift(newNode);
    }
    return true;
  }

  /**
   * 添加包装器（如果可能）
   */
  addWrapperIfPossible() {
    if (this.children.length === 1) {
      const child = this.children[0];
      if (child.type === ConditionTypeEnum.THEN) {
        this.children = child.children;
        this.children.forEach(child => {
          child.parent = this;
        });
      }
    }
  }

  /**
   * 移除当前节点
   */
  remove() {
    return false; // Chain节点不能被移除
  }
} 